/**
 * Bing每日一图插件 - React组件
 * 包含JSX语法的UI组件
 */

import React, { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { 
  Download, 
  Upload, 
  RefreshCw, 
  Image as ImageIcon, 
  Calendar, 
  ExternalLink,
  Loader2
} from 'lucide-react'
import { toast } from 'sonner'

const BingDailyImagePage = () => {
  const [imageData, setImageData] = useState(null)
  const [isLoading, setIsLoading] = useState(false)
  const [isUploading, setIsUploading] = useState(false)
  const [bucketName, setBucketName] = useState('default-bucket')

  // 获取Bing图片
  const fetchBingImage = useCallback(async () => {
    setIsLoading(true)
    try {
      const response = await fetch('https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1')
      const data = await response.json()
      
      if (data.images && data.images.length > 0) {
        const image = data.images[0]
        setImageData({
          url: `https://www.bing.com${image.url}`,
          title: image.title,
          copyright: image.copyright,
          date: image.startdate
        })
        toast.success('图片加载成功')
      } else {
        toast.error('未找到图片数据')
      }
    } catch (error) {
      console.error('获取Bing图片失败:', error)
      toast.error('获取图片失败')
    } finally {
      setIsLoading(false)
    }
  }, [])

  // 下载图片
  const handleDownload = useCallback(async () => {
    if (!imageData) return
    
    try {
      const response = await fetch(imageData.url)
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `bing-${imageData.date}.jpg`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
      toast.success('图片下载成功')
    } catch (error) {
      console.error('下载图片失败:', error)
      toast.error('下载图片失败')
    }
  }, [imageData])

  // 上传到存储桶
  const handleUpload = useCallback(async () => {
    if (!imageData) return
    
    setIsUploading(true)
    try {
      // 这里调用插件的上传方法
      // 实际实现中会通过插件系统调用
      console.log('上传图片到存储桶:', bucketName)
      toast.success(`图片已上传到 ${bucketName}`)
    } catch (error) {
      console.error('上传图片失败:', error)
      toast.error('上传图片失败')
    } finally {
      setIsUploading(false)
    }
  }, [imageData, bucketName])

  // 组件挂载时获取图片
  useEffect(() => {
    fetchBingImage()
  }, [fetchBingImage])

  return (
    <div className="container mx-auto p-6">
      <div className="mb-6">
        <h1 className="text-3xl font-bold mb-2">Bing每日一图</h1>
        <p className="text-muted-foreground">
          获取每日Bing图片，支持下载和上传到存储桶
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 图片显示区域 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <ImageIcon className="h-5 w-5" />
              今日图片
            </CardTitle>
            <CardDescription>
              {imageData ? `拍摄日期: ${imageData.date}` : '正在加载...'}
            </CardDescription>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex items-center justify-center h-64">
                <Loader2 className="h-8 w-8 animate-spin" />
              </div>
            ) : imageData ? (
              <div className="space-y-4">
                <img
                  src={imageData.url}
                  alt={imageData.title}
                  className="w-full h-64 object-cover rounded-lg"
                />
                <div>
                  <h3 className="font-semibold mb-2">{imageData.title}</h3>
                  <p className="text-sm text-muted-foreground">
                    {imageData.copyright}
                  </p>
                </div>
              </div>
            ) : (
              <div className="flex items-center justify-center h-64 text-muted-foreground">
                暂无图片
              </div>
            )}
          </CardContent>
        </Card>

        {/* 操作区域 */}
        <Card>
          <CardHeader>
            <CardTitle>操作面板</CardTitle>
            <CardDescription>
              管理图片下载和上传
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 刷新按钮 */}
            <Button
              onClick={fetchBingImage}
              disabled={isLoading}
              className="w-full"
              variant="outline"
            >
              {isLoading ? (
                <Loader2 className="h-4 w-4 animate-spin mr-2" />
              ) : (
                <RefreshCw className="h-4 w-4 mr-2" />
              )}
              刷新图片
            </Button>

            {/* 下载按钮 */}
            <Button
              onClick={handleDownload}
              disabled={!imageData || isLoading}
              className="w-full"
            >
              <Download className="h-4 w-4 mr-2" />
              下载图片
            </Button>

            {/* 存储桶配置 */}
            <div className="space-y-2">
              <label className="text-sm font-medium">存储桶名称</label>
              <input
                type="text"
                value={bucketName}
                onChange={(e) => setBucketName(e.target.value)}
                className="w-full px-3 py-2 border rounded-md"
                placeholder="输入存储桶名称"
              />
            </div>

            {/* 上传按钮 */}
            <Button
              onClick={handleUpload}
              disabled={!imageData || isUploading}
              className="w-full"
              variant="default"
            >
              {isUploading ? (
                <Loader2 className="h-4 w-4 animate-spin mr-2" />
              ) : (
                <Upload className="h-4 w-4 mr-2" />
              )}
              上传到 {bucketName}
            </Button>

            {/* 状态信息 */}
            {imageData && (
              <div className="space-y-2">
                <div className="flex items-center gap-2">
                  <Calendar className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm">日期: {imageData.date}</span>
                </div>
                <div className="flex items-center gap-2">
                  <ExternalLink className="h-4 w-4 text-muted-foreground" />
                  <a
                    href={imageData.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-sm text-blue-500 hover:underline"
                  >
                    查看原图
                  </a>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

export default BingDailyImagePage
